from django.http import *

def set_by_key(objects):
    keys = []
    objects_set = []
    for obj in objects:
        if obj.key() not in keys:
            keys.append(obj.key())
            objects_set.append(obj)
    return objects_set

def get_by_str_id(cls, id):
    try:      
        id = int(id)
        return cls.get_by_id(id)
    except:
        return None
    
def get_by_str_id_or_name(cls, id_or_name):
    try:      
        if id_or_name[0] >= '0' and id_or_name[0] <= '9':
            id = int(id_or_name)
            return cls.get_by_id(id)
        else:
            return cls.get_by_key_name(id_or_name)
    except:
        return None    
    
#check whether a str is valid key name
def check_valid_key_name(key):
    if type(key) == str:
        key = unicode(key)
    
    if key[0] >= u'0' and key[0] <= u'9':
        return False
    
    if key[:2] == u'__' and key[-2:] == u'__':
        return False
    
    return True
    
#get query object, with or without filters
def build_query(cls, filters=None):
    query = cls.all()
    
    if filters is not None:
      for filter in filters:
        filter(query)

    return query

def _default_view(request):
    return HttpResponseNotFound()

#check id decorator
def check_id(cls, view=_default_view):
    def decorator(method):  
        def new_method(request, *args, **kwds):
            if not kwds.has_key('id'):
                return view(request)
            
            if get_by_str_id(cls, kwds['id']) is None:
                return view(request)
        
            return method(request, *args, **kwds)            
        return new_method
    return decorator

#check name decorator
def check_name(cls, prefix='', view=_default_view):
    def decorator(method):  
        def new_method(request, *args, **kwds):
            if not kwds.has_key('name'):
                return view(request)
            
            if cls.get_by_key_name(prefix+kwds['name']) is None:
                return view(request)
        
            return method(request, *args, **kwds)            
        return new_method
    return decorator

#check id or name decorator
def check_id_or_name(cls, prefix='', view=_default_view):
    def decorator(method):  
        def new_method(request, *args, **kwds):
            if not kwds.has_key('id_or_name'):
                return view(request)
            
            if kwds['id_or_name'][0] >= '0' and kwds['id_or_name'][0] <= '9':               
                if get_by_str_id(cls, kwds['id_or_name']) is None:
                    return view(request)
            else:
                if cls.get_by_key_name(prefix+kwds['id_or_name']) is None:
                    return view(request)
        
            return method(request, *args, **kwds)            
        return new_method
    return decorator
